package com.example.yunxiappbackend.controller;

import com.example.yunxiappbackend.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件的上传下载
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class UpLoadController {
    @Value("${staticResourcePath}")
    String staticResourcePath;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        if (file.isEmpty()) {
            return Result.error("文件为空");
        }
        log.info(file.toString());
        //1.使用UUID生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID() +suffix;
        //2.转存到程序资源目录
        File dir = new File(staticResourcePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(staticResourcePath,newFilename));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(newFilename);
    }

    @GetMapping("/download/{name}")
    public Result<String> download(@PathVariable String name, HttpServletResponse response){
        try {
            FileInputStream inputStream = new FileInputStream(new File(staticResourcePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            response.setContentType("image/jpeg");
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("下载成功");
    }
}
